package com.mysher.devlib.uvc;

import android.content.Context;

import com.mvcframework.mvccamera.Camera;
import com.mvcframework.mvccamera.IDeviceChangedListener;
import com.mvcframework.mvccamera.UsbDeviceControl;

import java.util.ArrayList;
import java.util.List;

public class UsbCameraMonitor {

    private static UsbCameraMonitor instance;
    private UsbDeviceControl usbDeviceControl = new UsbDeviceControl();
    private Camera[] cameras;

    private UsbCameraMonitor() {

    }

    /**
     * 获取实例
     *
     * @return 实例
     */
    public static synchronized UsbCameraMonitor getInstance() {
        if (instance == null) {
            instance = new UsbCameraMonitor();
        }
        return instance;
    }

    /**
     * 注册监听
     *
     * @param context
     */
    public void registerMonitor(Context context) {
        usbDeviceControl.initUsbManager(context);
        usbDeviceControl.registerUsbManager(new IDeviceChangedListener() {
            @Override
            public void onDeviceChanged(Camera[] cameras) {
                UsbCameraMonitor.this.cameras = cameras;
                for (IDeviceChangedListener listener : changedListeners) {
                    listener.onDeviceChanged(cameras);
                }
            }
        });
    }

    private List<IDeviceChangedListener> changedListeners = new ArrayList<>();

    /**
     * 添加设备变化回调
     *
     * @param listener 设备变化回调
     */
    public void addUsbCameraChangeListener(IDeviceChangedListener listener) {
        changedListeners.add(listener);
    }

    /**
     * 移除设备变化回调
     *
     * @param listener 设备变化回调
     */
    public void removeUsbCameraChangeListener(IDeviceChangedListener listener) {
        changedListeners.remove(listener);
    }

    /**
     * 反注册监听
     */
    public void unregisterMonitor() {
        changedListeners.clear();
        usbDeviceControl.unregisterUsbManager();
        usbDeviceControl.destroyUsbManager();
    }

    public UsbDeviceControl getUsbDeviceControl() {
        return usbDeviceControl;
    }

    /**
     * 获取所有uvc设备
     */
    public Camera[] getCameras() {
        return cameras;
    }

    public UvcCameraDev createUvcCameraDev(Camera camera) {
        return new UvcCameraDevImpl(usbDeviceControl, camera);
    }
}
